"""
Level progression system for tank battle game
"""
import sys
import os
from typing import Dict, List, Tuple, Optional

# Add src directory to path for imports
current_dir = os.path.dirname(os.path.abspath(__file__))
src_dir = os.path.dirname(current_dir)
if src_dir not in sys.path:
    sys.path.insert(0, src_dir)

from utils.constants import TankType
from utils.config import ENEMY_COUNT


class LevelManager:
    """Level progression and management system"""
    
    def __init__(self):
        """Initialize level manager"""
        self.current_level = 1
        self.max_level = 50  # Maximum level
        self.enemies_destroyed = 0
        self.total_enemies_destroyed = 0
        
        # Level progression settings
        self.base_enemy_count = ENEMY_COUNT
        self.enemy_count_increase = 1  # Additional enemies per level
        self.max_enemy_count = 15  # Maximum enemies per level
        
        # Level-specific settings
        self.level_settings = self._generate_level_settings()
    
    def _generate_level_settings(self) -> Dict[int, Dict]:
        """Generate settings for each level"""
        settings = {}
        
        for level in range(1, self.max_level + 1):
            # Calculate enemy count for this level
            enemy_count = min(
                self.base_enemy_count + (level - 1) * self.enemy_count_increase,
                self.max_enemy_count
            )
            
            # Calculate enemy type distribution
            enemy_distribution = self._calculate_enemy_distribution(level)
            
            # Calculate difficulty modifiers
            difficulty_modifier = self._calculate_difficulty_modifier(level)
            
            settings[level] = {
                'enemy_count': enemy_count,
                'enemy_distribution': enemy_distribution,
                'difficulty_modifier': difficulty_modifier,
                'map_density': min(0.4 + (level - 1) * 0.01, 0.6),  # Increasing map density
                'steel_density': min(0.1 + (level - 1) * 0.005, 0.2)  # Increasing steel density
            }
        
        return settings
    
    def _calculate_enemy_distribution(self, level: int) -> Dict[str, float]:
        """Calculate enemy type distribution for level"""
        if level <= 5:
            # Early levels: mostly basic enemies
            return {
                TankType.ENEMY_BASIC: 0.8,
                TankType.ENEMY_FAST: 0.2,
                TankType.ENEMY_HEAVY: 0.0
            }
        elif level <= 15:
            # Mid levels: mix of basic and fast
            return {
                TankType.ENEMY_BASIC: 0.6,
                TankType.ENEMY_FAST: 0.3,
                TankType.ENEMY_HEAVY: 0.1
            }
        else:
            # High levels: more challenging enemies
            return {
                TankType.ENEMY_BASIC: 0.4,
                TankType.ENEMY_FAST: 0.4,
                TankType.ENEMY_HEAVY: 0.2
            }
    
    def _calculate_difficulty_modifier(self, level: int) -> float:
        """Calculate difficulty modifier for level"""
        # Difficulty increases gradually
        return 1.0 + (level - 1) * 0.1
    
    def get_current_level(self) -> int:
        """Get current level"""
        return self.current_level
    
    def get_level_settings(self, level: Optional[int] = None) -> Dict:
        """Get settings for specified level or current level"""
        if level is None:
            level = self.current_level
        
        return self.level_settings.get(level, self.level_settings[1])
    
    def get_enemy_count_for_level(self, level: Optional[int] = None) -> int:
        """Get enemy count for specified level"""
        settings = self.get_level_settings(level)
        return settings['enemy_count']
    
    def get_enemy_distribution_for_level(self, level: Optional[int] = None) -> Dict[str, float]:
        """Get enemy distribution for specified level"""
        settings = self.get_level_settings(level)
        return settings['enemy_distribution']
    
    def get_difficulty_modifier_for_level(self, level: Optional[int] = None) -> float:
        """Get difficulty modifier for specified level"""
        settings = self.get_level_settings(level)
        return settings['difficulty_modifier']
    
    def get_map_settings_for_level(self, level: Optional[int] = None) -> Dict[str, float]:
        """Get map generation settings for level"""
        settings = self.get_level_settings(level)
        return {
            'brick_density': settings['map_density'],
            'steel_density': settings['steel_density']
        }
    
    def enemy_destroyed(self, tank_type: str):
        """Record enemy destruction"""
        self.enemies_destroyed += 1
        self.total_enemies_destroyed += 1
    
    def is_level_complete(self) -> bool:
        """Check if current level is complete"""
        required_enemies = self.get_enemy_count_for_level()
        return self.enemies_destroyed >= required_enemies
    
    def advance_level(self) -> bool:
        """
        Advance to next level
        
        Returns:
            True if level was advanced, False if at max level
        """
        if self.current_level >= self.max_level:
            return False
        
        self.current_level += 1
        self.enemies_destroyed = 0
        return True
    
    def reset_level(self):
        """Reset current level progress"""
        self.enemies_destroyed = 0
    
    def reset_game(self):
        """Reset entire game progress"""
        self.current_level = 1
        self.enemies_destroyed = 0
        self.total_enemies_destroyed = 0
    
    def get_level_progress(self) -> Dict:
        """Get current level progress information"""
        required_enemies = self.get_enemy_count_for_level()
        progress_percentage = (self.enemies_destroyed / required_enemies) * 100 if required_enemies > 0 else 0
        
        return {
            'current_level': self.current_level,
            'enemies_destroyed': self.enemies_destroyed,
            'required_enemies': required_enemies,
            'progress_percentage': progress_percentage,
            'total_enemies_destroyed': self.total_enemies_destroyed,
            'is_complete': self.is_level_complete()
        }
    
    def get_level_summary(self) -> Dict:
        """Get summary of level progression"""
        return {
            'current_level': self.current_level,
            'max_level': self.max_level,
            'total_enemies_destroyed': self.total_enemies_destroyed,
            'levels_completed': self.current_level - 1,
            'progress_percentage': ((self.current_level - 1) / self.max_level) * 100
        }
    
    def generate_enemy_list_for_level(self, level: Optional[int] = None) -> List[str]:
        """Generate list of enemy types for level"""
        if level is None:
            level = self.current_level
        
        settings = self.get_level_settings(level)
        enemy_count = settings['enemy_count']
        distribution = settings['enemy_distribution']
        
        enemies = []
        
        # Generate enemies based on distribution
        for tank_type, probability in distribution.items():
            count = int(enemy_count * probability)
            enemies.extend([tank_type] * count)
        
        # Fill remaining slots with basic enemies
        while len(enemies) < enemy_count:
            enemies.append(TankType.ENEMY_BASIC)
        
        return enemies[:enemy_count]  # Ensure we don't exceed count
